#include "FileData.h"

namespace FileData
{
    // Base64 编码函数
    std::string base64_encode(const uint8_t *data, size_t length)
    {
        static const char *base64_chars =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

        std::string encoded;
        int val = 0, valb = -6;
        for (size_t i = 0; i < length; i++)
        {
            val = (val << 8) + data[i];
            valb += 8;
            while (valb >= 0)
            {
                encoded.push_back(base64_chars[(val >> valb) & 0x3F]);
                valb -= 6;
            }
        }
        if (valb > -6)
        {
            encoded.push_back(base64_chars[((val << 8) >> (valb + 8)) & 0x3F]);
        }
        while (encoded.size() % 4)
        {
            encoded.push_back('=');
        }
        return encoded;
    }

    std::string fileDataToBase64(const std::string &imageData)
    {
        const uint8_t *data = reinterpret_cast<const uint8_t *>(imageData.data());

        std::string base64Image = base64_encode(data, imageData.size());

        // 将 Base64 字符串返回给 Node.js
        char *resultStr = new char[base64Image.size() + 1];
        std::strcpy(resultStr, base64Image.c_str());

        return resultStr;
    }
};
